<template>
  <!-- 价格设置 -->
  <div>
    <div style="font-size: 18px; color: #303133">
      <span>{{ matchMsg.name }}</span>
      <span class="md"
        >赛事时间：{{ matchMsg.matchDate }} ~ {{ matchMsg.matchEndDate }}</span
      >
    </div>
    <el-form :inline="true" class="pageWrap match_sign_date">
      <el-form-item label="赛事报名时间" class="nobot">
        <el-date-picker
          v-model="match_sign_date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy/MM/dd HH:mm:ss"
          format="yyyy/MM/dd HH:mm:ss"
          @change="putMatchSignDate()"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="是否开启报名">
        <el-switch
          v-model="state"
          active-text="开启"
          inactive-text="关闭"
          :active-value="1"
          :inactive-value="0"
          @change="putState"
        ></el-switch>
      </el-form-item>
    </el-form>
    <!-- accordion -->
    <el-collapse
      v-model="activeName"
      accordion
      class="pageWrap collapse"
      @change="getGroupSignMsg()"
    >
      <el-collapse-item v-for="(v, i) in groupArr" :key="i" :name="i">
        <template slot="title">
          <el-row class="collapseTit">
            <div class="ml">
              赛项名称：
              <span class="cu">{{ v.name }}</span>
            </div>
            <div>
              报名时间：
              <span class="cu">{{
                v.startTime ? v.startTime : " - - - "
              }}</span>
              至
              <span class="cu">{{ v.endTime ? v.endTime : " - - - " }}</span>
            </div>
            <div>
              总招募人数：
              <span class="cu">{{ v.recruitNum ? v.recruitNum : "暂无" }}</span>
            </div>
            <div>
              报名费：
              <span class="cu">{{ v.price ? v.price : "暂无" }}</span>
            </div>
          </el-row>
        </template>
        <el-form
          style="margin-top: 12px"
          label-width="130px"
          v-loading="loading"
        >
          <div v-if="v.matchGroups && v.matchGroups.length > 0">
            <div v-for="(vv, ii) in v.matchGroups" :key="ii" class="classPer">
              <div class="sfTit">{{ vv.name }}</div>
              <el-col :md="12" :sm="24">
                <el-form-item label="成员人数限制">
                  <el-input
                    v-model="vv.teamNum1"
                    placeholder="请输入最少成员数"
                    class="bashi"
                    @input="$forceUpdate()"
                  >
                    <template slot="append">人</template>
                  </el-input>
                  <el-input
                    v-model="vv.teamNum2"
                    placeholder="请输入最大成员数"
                    class="bashi"
                    @input="$forceUpdate()"
                  >
                    <template slot="append">人</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :md="12" :sm="24">
                <el-form-item label="价格">
                  <el-input
                    v-model="vv.price"
                    placeholder="请输入价格"
                    class="bashi"
                    @input="$forceUpdate()"
                  >
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </div>
            <el-col class="saveBtn">
              <el-button
                type="primary"
                @click="
                  saveSet(i, 'out', v.matchGroups);
                  saveGSet(v.matchGroups, 0);
                "
                >保存设置</el-button
              >
            </el-col>
          </div>
          <div v-else>
            <el-col :md="12" :sm="24">
              <el-form-item label="总招募人数">
                <el-input
                  v-model="v.recruitNum"
                  placeholder="请输入总招募人数"
                  class="bashi"
                  @input="$forceUpdate()"
                >
                  <template slot="append">人</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :md="12" :sm="24">
              <el-form-item label="价格">
                <el-input
                  v-model="v.price"
                  placeholder="请输入价格"
                  class="bashi"
                  @input="$forceUpdate()"
                >
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="报名信息是否审核">
                <el-switch
                  v-model="v.applyAudit"
                  :active-value="1"
                  :inactive-value="0"
                  active-text="需要审核"
                  inactive-text="无需审核"
                  @change="$forceUpdate()"
                ></el-switch>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="赛项报名时间">
                <el-date-picker
                  v-model="v.group_sign_date"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy/MM/dd HH:mm:ss"
                  format="yyyy/MM/dd HH:mm:ss"
                  class="bashi"
                  @input="$forceUpdate()"
                  @change="group_sign_date_change(i)"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="优惠策略">
                <el-button type="primary" @click="addTactics(i)"
                  >添加策略</el-button
                >
              </el-form-item>
              <el-table :data="v.discounts" style="width: 100%" border>
                <el-table-column label="策略名称" width="150">
                  <template slot-scope="{ row }">
                    <el-input
                      v-model="row.name"
                      placeholder="策略名称"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="类型" width="150">
                  <template slot-scope="{ row }">
                    <el-select v-model="row.type" placeholder="请选择">
                      <el-option label="报名时间" value="D"></el-option>
                      <!-- <el-option label="拼团报名" value="P"></el-option> -->
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="address" label="规则">
                  <template slot-scope="{ row }">
                    <el-date-picker
                      v-show="row.type == 'D'"
                      v-model="row.rule_date"
                      type="datetimerange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy/MM/dd HH:mm:ss"
                      format="yyyy/MM/dd HH:mm:ss"
                    ></el-date-picker>
                    <!-- <span v-if="row.type=='P'">拼团截止到报名时间截止，人数不足时自动退款</span> -->
                    <div v-show="row.type == 'P'">
                      <el-input
                        v-model="row.rule"
                        placeholder="拼团人数"
                        class="bashi"
                      >
                        <template slot="append">人</template>
                      </el-input>
                      <el-tooltip
                        class="item"
                        effect="dark"
                        content="拼团截止到报名时间截止，人数不足时自动退款"
                        placement="top"
                      >
                        <i
                          class="el-icon-warning-outline"
                          style="
                            font-size: 20px;
                            line-height: 40px;
                            margin-left: 5px;
                          "
                        ></i>
                      </el-tooltip>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="价格" width="150">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.price" placeholder="价格">
                      <template slot="append">元</template>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template slot-scope="{ $index }">
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      circle
                      @click="v.discounts.splice($index, 1)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <el-col class="saveBtn">
              <el-button type="primary" @click="saveSet(i)">保存设置</el-button>
            </el-col>
          </div>
        </el-form>
      </el-collapse-item>
    </el-collapse>
    <!-- 报名成功提示信息 -->
    <div class="pageWrap upTips">
      <p class="titTips">
        报名成功提示信息 <span class="initV">默认为 报名成功</span>
      </p>
      <RichTxt ref="editor" class="tipsCon"></RichTxt>
      <el-button type="primary" @click="putAlertInfo()">保存提示信息</el-button>
    </div>
  </div>
</template>

<script>
function compareDate(date1, date2) {
  var oDate1 = new Date(date1);
  var oDate2 = new Date(date2);
  if (oDate1.getTime() > oDate2.getTime()) {
    return true; //第一个大
  } else {
    return false; //第二个大
  }
}

//富文本
import RichTxt from "../../../components/editor/editor";
export default {
  components: { RichTxt },
  data() {
    return {
      activeName: 0,
      match_sign_date: [],
      matchMsg: "",
      groupArr: [],
      loading: false,
      state: 0,
    };
  },
  methods: {
    //修改赛事报名时间
    putMatchSignDate() {
      if (!this.match_sign_date || this.match_sign_date.length == 0) {
        this.$message.error("请先设置赛事报名时间");
        return false;
      }
      //   报名结束时间不得大于比赛开始时间
      // let cp = compareDate(this.match_sign_date[1], this.matchMsg.matchDate);
      // if (cp) {
      //   this.$message.error("报名结束时间不得大于比赛开始时间");
      //   this.match_sign_date = [];
      //   return false;
      // }
      let oo = {
        matchId: this.$Base64.decode(sessionStorage.getItem("MandA")),
        startTime: this.match_sign_date[0],
        endTime: this.match_sign_date[1],
      };
      this.$axios.post("/sbr/applySet/putMatchApplySet", oo).then((res) => {
        this.getMatchSignDate();
      });
    },
    putState() {
      this.$axios
        .get(
          "/sbr/applyForm/putMatchApplySetState/" +
            sessionStorage.getItem("MandA")
        )
        .then((res) => {
          this.getMatchSignDate();
        });
    },
    // 获取赛事报名时间
    getMatchSignDate() {
      this.$axios
        .get(
          "/sbr/applyForm/getMatchApplySet/" + sessionStorage.getItem("MandA")
        )
        .then((res) => {
          let rr = res.data.data;
          if (rr) {
            if (rr.startTime) {
              this.match_sign_date = JSON.parse(
                JSON.stringify([rr.startTime, rr.endTime])
              );
              this.groupArr.forEach((v) => {
                if (v.group_sign_date.length == 0) {
                  v.startTime = rr.startTime;
                  v.endTime = rr.endTime;
                  v.group_sign_date = JSON.parse(
                    JSON.stringify([rr.startTime, rr.endTime])
                  );
                }
              });
            }
            this.state = rr.state;
            this.$refs.editor.content = rr.alertInfo;
          }
          this.getAllSign();
        });
    },
    getAllSign() {
      this.$axios
        .get(
          "/sbr/applySet/getMatchApplySetInfo/" +
            sessionStorage.getItem("MandA")
        )
        .then((res) => {
          let rr = res.data.data;
          if (rr.length > 0) {
            rr.forEach((v) => {
              let i = this.groupArr.findIndex((s) => {
                return s.groupId == v.groupId;
              });

              v.group_sign_date = [v.startTime, v.endTime];
              v.discounts.forEach((s) => {
                if (s.type == "D") {
                  s.rule_date = s.rule.split(";");
                }
              });
              v.name = this.groupArr[i].name;
              v.matchId = this.$Base64.decode(sessionStorage.getItem("MandA"));
              v.matchGroups=this.groupArr[i].matchGroups
              this.groupArr[i] = v;
            });
          }
          this.getGroupSignMsg();
        });
    },
    // 获取赛事数据
    getMatch() {
      this.$axios
        .get("/sbr/match/getMatchById/" + sessionStorage.getItem("MandA"))
        .then((res) => {
          let rr = res.data.data;
          this.matchMsg = rr;
          let glist = []
          rr.matchInfo.forEach((v) => {
            let oo={}
            let mg = [];
            v.matchGroups.forEach((m) => {
              mg.push({
                matchId: this.$Base64.decode(sessionStorage.getItem("MandA")),
                name: m.name,
                groupId: m.id,
              });
            });
            oo= {
              name: v.name,
              groupId: v.id,
              discounts: [],
              matchId: this.$Base64.decode(sessionStorage.getItem("MandA")),
              recruitNum: "",
              price: "",
              endTime: "",
              startTime: "",
              group_sign_date: [],
              applyAudit: 0,
              matchGroups: mg
            };
            console.log(oo)
            glist.push(oo)
          });
          console.log(glist)
          this.groupArr = glist;
          this.getMatchSignDate();
        });
    },
    // 添加优惠策略
    addTactics(i) {
      let oo = {
        name: "",
        type: "D",
        rule: "",
        price: "",
        rule_date: [],
      };
      this.groupArr[i].discounts.push(JSON.parse(JSON.stringify(oo)));
    },
    group_sign_date_change(i) {
      if (this.groupArr[i].group_sign_date.length == 0) {
        this.groupArr[i].startTime = "";
        this.groupArr[i].endTime = "";
        return false;
      } else {
        //   赛项报名结束时间不得大于赛事报名结束时间
        // let cp = compareDate(this.groupArr[i].group_sign_date[1],this.match_sign_date[1]);
        // if (cp) {
        //   this.$message.error("赛项报名结束时间不得大于赛事报名结束时间");
        //   this.groupArr[i].group_sign_date=[]
        //   return false;
        // }
        this.groupArr[i].startTime = this.groupArr[i].group_sign_date[0];
        this.groupArr[i].endTime = this.groupArr[i].group_sign_date[1];
      }
      this.$forceUpdate();
    },
    // 保存设置
    saveSet(i, out, mg) {
      if (this.match_sign_date.length == 0) {
        this.$message.error("请先设置赛事报名时间");
        return false;
      }
      if (!out) {
        if (!this.groupArr[i].recruitNum) {
          this.$message.error("请设置总招募人数");
          return false;
        }
        if (
          Number(this.groupArr[i].price) < 0 ||
          isNaN(this.groupArr[i].price)
        ) {
          this.$message.error("无效价格");
          return false;
        }
      }
      if (mg) {
        this.groupArr[i].recruitNum = 0;
        let pp = mg.map((v) => {
          return v.price;
        });
        this.groupArr[i].price = Number(Math.min.apply(null, pp));
        this.groupArr[i].startTime= this.match_sign_date[0]
        this.groupArr[i].endTime= this.match_sign_date[1]
      }
        this.groupArr[i].teamRestrictNum = 0;
      if (this.groupArr[i].group_sign_date.length == 0) {
        this.$message.error("请设置报名时间");
        return false;
      }
      for (let a = 0; a < this.groupArr[i].discounts.length; a++) {
        let v = this.groupArr[i].discounts[a];
        if (!v.price) {
          this.$message.error("请设置优惠价格");
          return false;
        }
        if (Number(v.price) < 0 || isNaN(v.price)) {
          this.$message.error("无效优惠价格");
          return false;
        }
        if (v.type == "D") {
          v.rule = v.rule_date.join(";");
        }
      }
      // console.log(this.groupArr[i]);
      this.$axios
        .post("/sbr/applySet/putGroupApplySet", this.groupArr[i])
        .then((res) => {
          let rr = res.data.data;
          this.$message.success("保存成功");
        });
    },
    // 获取赛项报名信息
    getGroupSignMsg() {
      if (this.activeName === "") return false;
      this.loading = true;
      let gId = this.groupArr[this.activeName].groupId;
      this.$axios
        .get("/sbr/applySet/getGroupApplySet/" + this.$Base64.encode(gId))
        .then((res) => {
          let rr = res.data.data;
          if (rr) {
            if (this.groupArr[this.activeName].matchGroups&&this.groupArr[this.activeName].matchGroups.length > 0) {
              if (rr.lists.length > 0) {
                this.groupArr[this.activeName].matchGroups.forEach((v) => {
                  let i = rr.lists.findIndex((s) => {
                    return s.groupId == v.groupId;
                  });
                  if (i >= 0) {
                    let tn=rr.lists[i].teamRestrictNum
                    v.teamRestrictNum = tn;
                    v.teamNum1=tn.split(';')[0]
                    v.teamNum1=v.teamNum1?v.teamNum1:1
                    v.teamNum2=tn.split(';')[1]
                    v.price = rr.lists[i].price;
                  }
                  // let emp=rr.lists.map(s=>{return s.price})
                  // v.fp=Math.min.apply(null, emp)+'元/起'
                });
              }
            } else {
              rr.group_sign_date = [rr.startTime, rr.endTime];
              rr.discounts.forEach((v) => {
                if (v.type == "D") {
                  v.rule_date = v.rule.split(";");
                }
              });
              rr.groupId = this.groupArr[this.activeName].groupId;
              rr.name = this.groupArr[this.activeName].name;
              rr.matchId = this.$Base64.decode(sessionStorage.getItem("MandA"));
              rr.matchGroups=this.groupArr[this.activeName].matchGroups
              this.groupArr[this.activeName] = rr;
            }
          }
          this.loading = false;
        });
    },
    saveGSet(mg, i) {
      console.log(mg);
      mg[i].teamRestrictNum=mg[i].teamNum1+';'+mg[i].teamNum2
      mg[i].recruitNum = 0;
      mg[i].startTime = this.match_sign_date[0];
      mg[i].endTime = this.match_sign_date[1];
      mg[i].applyAudit = 0;
      this.$axios.post("/sbr/applySet/putGroupApplySet", mg[i]).then((res) => {
        let rr = res.data.data;
        if (++i < mg.length) {
          this.saveGSet(mg, i);
        } else this.$message.success("保存成功");
      });
    },
    // 报名成功提示信息
    putAlertInfo() {
      let oo = {
        matchId: this.$Base64.decode(sessionStorage.getItem("MandA")),
        alertInfo: this.$refs.editor.content,
      };
      this.$axios
        .post("/sbr/applySet/putMatchApplyAlertInfo", oo)
        .then((res) => {
          this.$message.success("提示信息保存成功");
          this.getMatchSignDate();
        });
    },
  },
  created() {
    this.getMatch();
  },
};
</script>
<style scoped>
/* @import url(); 引入公共css类 */
.md {
  margin-left: 10px;
}
.match_sign_date {
  margin: 14px auto;
}
.nobot {
  margin-bottom: 0;
}
.collapseTit {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.collapse >>> .el-collapse-item__header {
  background-color: #ebf4f2;
}
.bashi {
  width: 80%;
  float: left;
}
.saveBtn {
  margin: 10px auto;
  text-align: center;
}
.upTips {
  margin: 14px auto;
}
.titTips {
  font-size: 18px;
}
.tipsCon {
  margin: 14px auto;
}
.initV {
  font-size: 14px;
}
.sfTit {
  width: 100%;
  text-align: center;
  font-size: 22px;
  font-weight: bold;
}
.classPer {
  margin-bottom: 10px;
  border-bottom: 1px solid #f2f2f2;
  overflow: hidden;
}
</style>